package br.com.locautowebbd.cor;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.locautowebbd.util.HibernateConnectionUtil;
import br.com.locautowebbd.util.RepositorioException;

public class RepositorioCorJPA implements RepositorioCores {

	public void atualizar(Cor cor)
			throws CorInexistenteException, RepositorioException {
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();

			if (!existe(cor.getCodigo())) {
				throw new CorInexistenteException(cor.getCodigo());

			}

			session.update(cor);
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}

	}

	@Override
	public boolean existe(int codigo) throws RepositorioException {
		boolean resp = false;
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			Cor procurado = (Cor) session.get(Cor.class,
					codigo);
			resp = procurado != null;
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}
		return resp;
	}

	@Override
	public void inserir(Cor novoCor)
			throws CorExistenteException, RepositorioException {
		try {
			if (!existe(novoCor.getCodigo())) {
				Session session = HibernateConnectionUtil.getSession();
				Transaction t = session.beginTransaction();
				session.save(novoCor);
				session.flush();
				t.commit();
			}
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}
	}

	@Override
	public Cor procurar(int codigo)
			throws CorInexistenteException, RepositorioException {
		Cor resp = null;
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			resp = (Cor) session.get(Cor.class, codigo);

			if (resp == null) {
				throw new CorInexistenteException(codigo);

			}
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);

		}
		return resp;
	}

	@Override
	public void remover(int codigo) throws CorInexistenteException,
			RepositorioException {
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			Cor procurado = (Cor) session.get(Cor.class, codigo);

			if (procurado == null) {
				throw new CorInexistenteException(codigo);

			}
			session.delete(procurado);
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);

		}
	}

}
